/**
 * Location alert Dialog.
 */
var LocChatGroupDialog = (function() {

    var mapTmp = [
        '<div class="card">', 
            '<div class="map-wrapper-google"></div>', 
        '</div>'
    ].join('');

    var chatGroupForm = [
        '<form class="ujsForm" style="display:none;height:215px;width:214px;">',
            '<div class="formItem" style="padding:2px;">', 
                '<label style="width: 90px;" lan="lbl.callFor"></label>', 
                '<div class="formField customFormField memberSelector2"></div>', 
            '</div>', 
            '<div class="formItem" style="padding:2px;">', 
                '<label style="width: 90px;" for="title" lan="lbl.title"></label>', 
                '<input id="title" class="formInput placeName" style="width:206px;"/>', 
            '</div>', 
            '<div class="formItem" style="padding:2px;margin-bottom:8px;">', 
                '<label style="width:90px;display:block;" for="range" lan="lbl.distance"></label>', 
                '<input id="range" class="formInput" value="5" style="width:60px;"/> km', 
                '<button class="startBtn" style="border:solid 1px #858282;line-height:28px;padding:0px 9px;font-weight: bold;letter-spacing:1px;border-radius:3px;margin-left:70px;" lan="dialog.buttons.start"></button>', 
            '</div>',           
        '</form>'
    ].join('');
    
    /**
     * 默认配置.
     */
    var defConfig = {
        zoom : 16,
        defLocation : {
            latitude : 40,
            longitude : 40
        }
    };

    /**
     * 构造函数.
     */
    var _groupManageDialog = function(config) {
        var _this = this;   
        _this.config = $.extend(_this.config, defConfig, config);     
        this.setProps({
            size : {
                width : $(window).width() - 60,
                height : $(window).height() - 40
            }
        });        
        this.addDialogContent(mapTmp, function($dialogContent) {
            _this.on('inital', function(){       
                ujs.subjects.map.GoogleMapAPI.load(function(){         
                    _this.showMask('loading');
                    ujs.browser.geo.getCurrentPosition(function(position){
                        _this.initLocation(position.coords);
                    }, function(){                        
                        _this.initLocation(_this.config['defLocation']);                    
                        bubble.msg(lan('location.getLocFailedTip'));
                    });
                    _this.showGroupForm();
                }, _this.$dialogContent);                    
            });
        });
        this.on('fullscreenChanged', function() {
            if(_this.map){
                google.maps.event.trigger(_this.map, 'resize');
            }
        });
    }.extend(ujs.ui.Dialog);

    _groupManageDialog.prototype.initLocation = function(pos) {
        var _this = this,
            latlon = new google.maps.LatLng(pos['latitude'], pos['longitude']);        
        /**
         * @property map 当前地图对象.
         * @type Map
         */
        this.map = new google.maps.Map(
            _this.$wrapper.find('.map-wrapper-google').get(0),
            $.extend({}, ujs.subjects.map.GoogleMapAPI.mapDefConfig, {
                center : latlon,
                zoom : _this.config['zoom']
            })
        );
        this.map.addListener('idle', function() {            
            _this.hideMask();
        });
        this.map.addListener("click", function(event) {            
            _this.showForm(event.latLng);
        });
        this.map.addListener("rightclick", function(event) {
            _this.showForm(event.latLng);
        });

        /**
         * @property searchBox
         * @type google.maps.places.SearchBox
         */
        this.searchBox = ujs.subjects.map.GoogleMapAPI.util.addSeachBox(_this.map, {
            cls : 'pac-input controls',            
            placeholder : lan('location.searchLocTip')
        }, {
            url : '/ujs/app/im/images/marker/16.png',
            size : new google.maps.Size(16, 16),
            origin : new google.maps.Point(0, 0)
        }, {
            click : function(place){
                if (_this.marker) {
                    _this.marker.setVisible(false);
                }
                var markerSelf = this, 
                    $settingForm = _this.getDialogLayer('settingForm');
                _this.currentMarkerPos = this.position;
                $settingForm.show();
                (function(){
                    $settingForm.find('.placeName').val(place.name);
                    _this.infowindow.open(_this.map, markerSelf);
                }).defer(5);
            }
        });
    };

    _groupManageDialog.prototype.showGroupForm = function() {
        var _this = this, 
            formLayerID = 'settingForm';
        this.addDialogLayer(formLayerID, chatGroupForm, function($dialogContent) {            
            _this.memberSelector = new MemberSelector($dialogContent.find('.memberSelector2'), {
                size : {
                    width : 210,
                    height : 80
                },
                memberStyle : {
                    width : 220,
                    minWidth : 220,
                    // height : 201,
                },
                treeType : 'locationalert',
                treePos : 'right',
                exclusion : [ujs.util.session.getCurrentUserID()],
                events : {
                    rootLoaded : function(roots) {
                        for (var i = 0; i < roots.length; i++) {
                            var root = roots[i],
                                attr = root['attr'];
                            if (root['data'] && attr['cr'] === undefined)
                                _this.memberSelector.addMember(attr['id'], root['data'], attr['icon'], attr['rel']);
                        }
                    }
                }
            });
            //启动location alert.
            $dialogContent.find('.startBtn').click(function() {
                var formData = _this.getFormData();
                var members = _this.memberSelector.getUserAndGroup();                
                if(!formData){
                    bubble.msg(lan('form.noBlankTitle'));
                    return false;
                }                
                if(!members['groups'].length && !members['users'].length){
                    bubble.msg(lan('form.selMembers'));
                    return false;
                }                
                _this.showMask(lan('common.creating', 'location alert'));                
                $(this).disable();
                //保存或更新.                
                page.biz.createChatGroup(formData, function(msg) {
                    page.biz.addChatGroupLocal(msg);
                    var teid = msg['te']['id'];
                    sessionList.startSession(teid, 'newLocAlert');

                    var formData = ujs.browser.form.getValues(_this.getForm()), 
                        members = _this.memberSelector.getUserAndGroup();

                    $.ajax({
                        type : 'post',
                        url : '/apis/location/request/in',
                        data : {
                            lo : _this.currentMarkerPos.lng(),
                            la : _this.currentMarkerPos.lat(),
                            m : parseInt(formData['range']) * 1000,
                            id : teid,
                            ugids : members['groups'],
                            uids : members['users']
                        },
                        success : ujs.hr(function(msg) {
                            page.mapLoc[teid] = _this.currentMarkerPos;
                            _this.remove();
                        })
                    });
                });
                return false;
            });
            _this.infowindow = new google.maps.InfoWindow({
                content : $dialogContent.get(0),                
                disableAutoPan : true,
                maxWidth : 196
            });
        });
    };
    
    _groupManageDialog.prototype.showForm = function(latLng){
        var _this = this;
        if (_this.marker) {
            _this.marker.setVisible(false);
        }
        var marker = new google.maps.Marker({
            map : _this.map,
            icon : {
                url : '/ujs/app/im/images/marker/16.png', //place.icon,
                size : new google.maps.Size(16, 16),
                origin : new google.maps.Point(0, 0)
            },
            title : '',
            position : latLng
        });
        _this.marker = marker;
        google.maps.event.addListener(marker, 'click', function() {
            var markerSelf = this, $settingForm = _this.getDialogLayer('settingForm');
            _this.currentMarkerPos = this.position;
            $settingForm.show();
            (function(){
                $settingForm.find('.placeName').val('');
                _this.infowindow.open(_this.map, markerSelf);

                ujs.subjects.map.GoogleMapAPI.util.getPlaces(latLng, function(addrs, addr) {
                    $settingForm.find('.placeName').val(addr);
                });
            }).defer(5);
        });

        var $settingForm = _this.getDialogLayer('settingForm');
        _this.currentMarkerPos = latLng;
        $settingForm.show();
        (function(){
            $settingForm.find('.placeName').val('');
            _this.infowindow.open(_this.map, marker);

            ujs.subjects.map.GoogleMapAPI.util.getPlaces(latLng, function(addrs, addr) {
                $settingForm.find('.placeName').val(addr);
            });
        }).defer(5);
    };

    /**
     * 获取表单数据.
     */
    _groupManageDialog.prototype.getFormData = function() {
        var _this = this;
        var formData = ujs.browser.form.getValues(this.getForm()), 
            lat = _this.currentMarkerPos.lat(), 
            lng = _this.currentMarkerPos.lng(), 
            uid = ujs.util.session.getCurrentUserID(), 
            zoom = _this.map.getZoom(),
        
        //基础数据.
        data = {
            type : 'locationalert',
            ugids : [],
            uids : [uid],
            auids : [uid],
            title : formData['title'],
            la : lat,
            lo : lng,
            zoom : zoom,
            distanceMeters : formData['range'] * 1000,
            icon : 'http://maps.googleapis.com/maps/api/staticmap?' + $.param({
                center : '{0},{1}'.format(lat, lng),
                size : '150x150',
                zoom : zoom,
                sensor : false,
                markers : 'color:{0}|label:{1}|{2},{3}'.format('red', formData['title'], lng, lat)
            }),
            allowBroadcast : false,
            allowDelete : false,
            allowDestruct : false,
            allowLocation : true,
            allowParticipant : false,
            allowDismiss : false
        };
        
        if(!formData['title']){
            return false;    
        }
        //chat group图标.
        return Object.toFormData({
            chat : JSON.stringify(data)
        });
    };
    return _groupManageDialog;
})(); 